package com.infore.airsupervise.adapter;

import android.graphics.Color;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.infore.airsupervise.R;
import com.infore.airsupervise.bean.PointQueryE;
import com.infore.airsupervise.ui.widget.MyMarkerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * Created by xiaotao on 2017/8/4.
 */

public class PointDataQueryAdapter extends RecyclerView.Adapter<PointDataQueryAdapter.ViewHolder> {

    private List<PointQueryE> sourceData;
    private int sel_position = -1;
    private String cur_factor = "AQI";
    private AlphaAnimation showAnimation;
    private AlphaAnimation hideAnimation;

    public PointDataQueryAdapter(List<PointQueryE> sourceData) {
        this.sourceData = sourceData == null ? new ArrayList<PointQueryE>() : sourceData;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_point_data_query, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final LineChart mChart = holder.itemBarChart;
        final PointQueryE pointQueryE = sourceData.get(position);
        PointQueryE.ExpandValueBean expandBean = pointQueryE.getExpandBean();
        holder.tvStationName.setText(pointQueryE.getName());
        getLastFactorValue(pointQueryE.getVlist(),holder);
        holder.sgFactor.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

                switch (checkedId) {
                    case R.id.rb_AQI:
                        cur_factor = "AQI";
                        break;
                    case R.id.rb_PM10:
                        cur_factor = "PM10";
                        break;
                    case R.id.rb_PM25:
                        cur_factor = "PM2.5";
                        break;
                    case R.id.rb_SO2:
                        cur_factor = "SO2";
                        break;
                    case R.id.rb_NO2:
                        cur_factor = "NO2";
                        break;
                    case R.id.rb_O3:
                        cur_factor = "O3";
                        break;
                    case R.id.rb_CO:
                        cur_factor = "CO";
                        break;
                }

                setChartData(mChart, getListByFactor(cur_factor, pointQueryE.getVlist()));
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sel_position != position) {
                    sel_position = position;
                    notifyDataSetChanged();
                }
            }
        });
        if (sel_position == position) {
            if(showAnimation == null){
                initShowAnimation();
            }
            holder.layoutChart.startAnimation(showAnimation);
            holder.layoutChart.setVisibility(View.VISIBLE);
            if (mChart.getTag() == null) {
                cur_factor = "AQI";
                initChart(mChart, getListByFactor(cur_factor, pointQueryE.getVlist()));
                mChart.setTag(true);
            }
        } else if(holder.layoutChart.getVisibility() == View.VISIBLE){
            if(hideAnimation == null){
                initHideAnimation();
            }
            holder.layoutChart.startAnimation(hideAnimation);
            holder.layoutChart.setVisibility(View.GONE);
        }

    }

    @Override
    public int getItemCount() {
        return sourceData == null ? 0 : sourceData.size();
    }


    class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.item_bar_chart)
        LineChart itemBarChart;
        @BindView(R.id.layout_chart)
        LinearLayout layoutChart;
        @BindView(R.id.sg_factor)
        SegmentedGroup sgFactor;
        @BindView(R.id.tv_station_name)
        TextView tvStationName;
        @BindView(R.id.tv_time)
        TextView tvTime;
        @BindView(R.id.tv_value_AQI)
        TextView tvValueAQI;
        @BindView(R.id.tv_value_PM25)
        TextView tvValuePM25;
        @BindView(R.id.tv_value_PM10)
        TextView tvValuePM10;
        @BindView(R.id.tv_value_SO2)
        TextView tvValueSO2;
        @BindView(R.id.tv_value_NO2)
        TextView tvValueNO2;
        @BindView(R.id.tv_value_CO)
        TextView tvValueCO;
        @BindView(R.id.tv_value_O3)
        TextView tvValueO3;
        @BindView(R.id.tv_tem)
        TextView tvTem;


        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * 初始化图标
     *
     * @param mChart
     */
    private void initChart(LineChart mChart, List<PointQueryE.VlistBean.FactorListBean> vlist) {

        mChart.getLegend().setEnabled(false);
        mChart.setScaleYEnabled(false);
        mChart.getDescription().setEnabled(false);
        mChart.setNoDataText("暂无该因子数据");
        // 动画时间
        mChart.animateX(1000);
        MyMarkerView mv = new MyMarkerView(mChart.getContext(), R.layout.custom_marker_view);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart
        //x轴
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisLineColor(Color.BLUE);
        xAxis.setDrawLabels(false); //是否绘制标签
        xAxis.setDrawGridLines(false);
        // 左Y轴
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setDrawGridLines(false);
        // leftAxis.setGranularityEnabled(true);
        leftAxis.setTextColor(Color.DKGRAY);
        leftAxis.setAxisLineColor(Color.BLUE);
        leftAxis.setSpaceTop(25f);//最高位置距离顶部的位置

        // 右Y轴
        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);

        setChartData(mChart, vlist);
    }


    private void setChartData(LineChart mChart, List<PointQueryE.VlistBean.FactorListBean> vlist) {
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        if (vlist == null) {
            return;
        }
        for (int i = 0; i < vlist.size(); i++) {
            PointQueryE.VlistBean.FactorListBean factor = vlist.get(i);
            yVals1.add(new Entry(i, (float)factor.getValue(), "时间："+factor.getTime()+"\n"+"数值： "+factor.getValue()));
        }
        LineDataSet set1;
        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.animateX(1000);
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        } else {
            set1 = new LineDataSet(yVals1, "");
            set1.setDrawCircles(true);
            set1.setLineWidth(2f);
            set1.setColor(Color.CYAN);
            set1.setCircleColor(Color.CYAN);
            set1.setCircleRadius(2.5f);
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            LineData lineData = new LineData(set1);
            lineData.setValueFormatter(new DefaultValueFormatter(2));
            mChart.setData(lineData);
        }
    }

    /**
     * 获取对应因子的数据集合
     */
    private List<PointQueryE.VlistBean.FactorListBean> getListByFactor(String factorName, List<PointQueryE.VlistBean> vlist) {
        for (PointQueryE.VlistBean vlistBean : vlist) {
            if (TextUtils.equals(factorName, vlistBean.getFactorName())) {
                return vlistBean.getFactorList();
            }
        }
        return null;
    }

    private void getLastFactorValue(List<PointQueryE.VlistBean> vlist ,ViewHolder holder){
        for (PointQueryE.VlistBean vlistBean : vlist) {
            double last_value = vlistBean.getFactorList().get(vlistBean.getFactorList().size()-1).getValue();
            if(TextUtils.equals("AQI", vlistBean.getFactorName())){
                holder.tvValueAQI.setText(last_value+"");
            }else if(TextUtils.equals("PM10", vlistBean.getFactorName())){
                holder.tvValuePM10.setText(last_value+"");
            } else if(TextUtils.equals("PM2.5", vlistBean.getFactorName())){
                holder.tvValuePM25.setText(last_value+"");
            } else if(TextUtils.equals("SO2", vlistBean.getFactorName())){
                holder.tvValueSO2.setText(last_value+"");
            } else if(TextUtils.equals("NO2", vlistBean.getFactorName())){
                holder.tvValueNO2.setText(last_value+"");
            } else if(TextUtils.equals("CO", vlistBean.getFactorName())){
                holder.tvValueCO.setText(last_value+"");
            }else if(TextUtils.equals("O3", vlistBean.getFactorName())){
                holder.tvValueO3.setText(last_value+"");
            }
        }
    }

    private void initShowAnimation(){
        showAnimation = new AlphaAnimation(0f,1f);
        showAnimation.setDuration(300);
    }
    private void initHideAnimation(){
        hideAnimation =  new AlphaAnimation(1f,0f);
        hideAnimation.setDuration(300);

    }
}
